<!DOCTYPE html>
<html lang="en">
<head>
    <title>文章管理</title>
    {% include 'admin/common/header.html' %}
    <link rel="stylesheet" href="{{ url_for('static', filename='/admin/admin/css/other/user.css') }}"/>
</head>
<body class="pear-container">
{# 查询表单 #}
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="" lay-filter="user-query-form">
            <div class="layui-form-item">
                <label class="layui-form-label">标题</label>
                <div class="layui-input-inline">
                    <input type="text" name="title" id="title" placeholder="" class="layui-input">
                </div>
                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="article-query">
                    <i class="layui-icon layui-icon-search"></i>
                    查询
                </button>
                <button type="reset" class="pear-btn pear-btn-md">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </form>
    </div>
</div>
<div class="user-left user-collasped">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="button button-primary user-group" user-group=""> 全部文章</div>
            <div class="button button-default user-group" user-group="-1"> 默认分类</div>
            <div style="overflow: auto">
                <ul id="category-tree" class="category-tree" data-id="0"></ul>
            </div>
        </div>
    </div>
</div>
{# 用户表格 #}
<div class="user-main user-collasped">
    <div class="layui-card">
        <div class="layui-card-body">
            <table id="article-table" lay-filter="article-table"></table>
        </div>
    </div>
</div>
</body>
{# 表格操作 #}
<script type="text/html" id="article-toolbar">
    {% if authorize("admin:article:add") %}
        <button class="pear-btn pear-btn-primary pear-btn-md"  data-title="新建文章"  lay-event="add">
            <i class="pear-icon pear-icon-add"></i>
            新增文章
        </button>

    {% endif %}
    {% if authorize("admin:user:remove") %}
        <button class="pear-btn pear-btn-md" lay-event="batchRemove">
            <i class="pear-icon pear-icon-ashbin"></i>
            删除
        </button>
    {% endif %}
    <button class="pear-btn pear-btn-md" lay-event="collasped">
        <i class="pear-icon pear-icon-modular"></i>
        高级
    </button>
</script>

{# 用户修改操作 #}
<script type="text/html" id="article-bar">
    {% if authorize("admin:user:edit") %}
        <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i class="pear-icon pear-icon-edit"></i>
        </button>
    {% endif %}
    {% if authorize("admin:user:remove") %}
        <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i
                class="pear-icon pear-icon-ashbin"></i>
        </button>
    {% endif %}
</script>
{# 标题模板 #}
<script type="text/html" id="article-title">
{{ "{{# if(d.allsort==1){ }} <span class=layui-badge>头条</span> {{# } }}" | safe}}
 <a href={{ "{{#  if(d.linkurl){ }} {{ d.linkurl }}{{#  } else {  }}../../{{ d.articleId }}{{#  } }} " }}
            class="layui-table-link" target="_blank">{{ "{{d.title}}" }}</a>
</script>
{# 启动与禁用 #}
<script type="text/html" id="article-enable">
    <input type="checkbox" name="enable" value="{{ "{{ d.articleId }}" }}" lay-skin="switch" lay-text="已审|待审"
           lay-filter="article-enable"
            {{ "{{# if(d.status==1){ }} checked {{# } }}" }} />
</script>
{# 文章发布时间 #}
<script type="text/html" id="article-releaseTime">
    {{ '  {{layui.util.toDateString(d.releaseTime,  "yyyy-MM-dd HH:mm:ss")}' |safe }}}
</script>
<script type="text/html" id="article-sort">
    {{ '{{getsortstr(d.sort)}}' }}
</script>
{% include 'admin/common/footer.html' %}
<script>
  let getsortstr=function (dsort){return dsort<0?'<span class="layui-badge layui-bg-orange">置顶</span>':dsort}
  layui.use(['table', 'dtree', 'form', 'jquery', 'popup', 'common','util'], function () {
    let table = layui.table
    let util = layui.util
    let form = layui.form
    let $ = layui.jquery
    let dtree = layui.dtree
    let popup = layui.popup
    let common = layui.common
    let MODULE_PATH = '/admin/article/'

    // 表格数据
    let cols = [
      [
        {% if authorize("admin:user:main") %}
          { type: 'checkbox' },
        {% endif %}
        { title: 'ID', field: 'articleId', align: 'left',width: 80 },
        { title: '标题', field: 'title', templet: '#article-title' },
        { title: '分类名称', field: 'categoryname', width:100,  align: 'center' },
        { title: '作者', field: 'author', align: 'center', width: 80},
        { title: '排序', field: 'sort', align: 'center', templet:'#article-sort', width: 90,edit: 'text' },
        { title: '状态', field: 'status', align: 'center', templet: '#article-enable', width: 100 },
        { title: '发布时间', field: 'releaseTime', templet: '#article-releaseTime', align: 'center', width: 180 },
        { title: '操作', toolbar: '#article-bar', align: 'center', width: 130 }
      ]
    ]
    // 渲染表格数据
    table.render({
      elem: '#article-table',
      url: MODULE_PATH + 'data',
      page: true,
      title:"内容-文章列表"+ new Date().getTime(),
      cols: cols,
      skin: 'line',
      height: 'full-148',
      toolbar: '#article-toolbar', /*工具栏*/
      text: { none: '暂无内容' },
        limit:12,
      defaultToolbar: [{ layEvent: 'refresh',title:'刷新', icon: 'layui-icon-refresh' }, 'filter', 'print', { layEvent: 'MY_EXPORT',title:'导出Excel', icon: 'layui-icon-export' }] /*默认工具栏*/
    })
   //监听单元格编辑
    table.on('edit(article-table)', function(obj){
        let value = obj.value //得到修改后的值
        ,data = obj.data //得到所在行所有键值
        ,field = obj.field; //得到字段
        //layer.msg('[ID: '+ data.sort +'] ' + field + ' 字段更改值为：'+ util.escape(value));
        let loading = layer.load()
        $.ajax({
        url: '/admin/article/editfield',
        data: JSON.stringify({ id: data.articleId, field:field, value:value}),
        dataType: 'json',
        contentType: 'application/json',
        type: 'put',
        success: function (result) {
          layer.close(loading)
          if (result.success) {
            popup.success(result.msg)
              window.refresh()
          } else {
            popup.failure(result.msg)
          }
        }
      })
   });
    // 树状图菜单
    let cate=dtree.render({
      elem: '#category-tree',
      method: 'get',
      url: '/admin/category/tree',
      dataFormat: 'list',
      line: true,
      skin: 'laySimple',
      icon: '-1',
      initLevel: "4",
      response: { treeId: 'categoryId', parentId: 'parentId', title: 'categoryName' },
      done: function(result, $ul, first){//只显示文章分类下的所有分类
        //console.log(result,first)
        // 设置第一个分类禁用后搜索显示想显示的总分类
        if(result.data.length>0) {
            result.data.forEach(function (e) {
                let childlist = cate.queryListTreeByPid(e.categoryId, result.data);
                if (childlist.length > 0) {
                    cate.setDisabledNodes(e.categoryId);
                }
            });
            cate.searchNode('文章分类');
        }
     }
    })
    // 菜单栏渲染
    dtree.on('node(\'category-tree\')', function (obj) {
      let field = form.val('user-query-form') /*用户账号查询*/
      field.categoryid = obj.param.nodeId
      window.refresh(field)
    })
    $('.user-group').click(function () {
      let group = $(this).attr('user-group')
      let field = form.val('user-query-form')
      if (group === '-1') {
        field.categoryid = group
        $(this).removeClass('button-default')
        $(this).prev().removeClass('button-primary')
        $(this).prev().addClass('button-default')
        $(this).addClass('button-primary')
      } else {
        field.categoryid = group
        $(this).removeClass('button-default')
        $(this).next().removeClass('button-primary')
        $(this).next().addClass('button-default')
        $(this).addClass('button-primary')
      }
      window.refresh(field)
    })

    table.on('tool(article-table)', function (obj) {
      if (obj.event === 'remove') {
        window.remove(obj)
      } else if (obj.event === 'edit') {
        window.edit(obj)
      }
    })

    table.on('toolbar(article-table)', function (obj) {
      if (obj.event === 'add') {
          console.log(obj)
          {#parent.layui.tab.addTabOnlyByElem("content", {#}
			{#			id:$(this).attr("data-id"),#}
			{#			title: $(this).attr("data-title"),#}
			{#			url: MODULE_PATH+"/add",#}
			{#			close: true#}
			{#		})#}
        layer.open({
        type: 2,
        title: '新增文章',
        area: ['1350px', '800px'],
        content: MODULE_PATH + 'add/0',
        maxmin: true,
        offset: 't',
        scrollbar: false,
        anim:2,
      })
          //parent.layer.full(addarticle);

      } else if (obj.event === 'refresh') {
        window.refresh()
      } else if (obj.event === 'batchRemove') {
        window.batchRemove(obj)
      }else if(obj.event==='MY_EXPORT')
      {
           let excels = null;
            $.ajax({
                url: MODULE_PATH+"exportdata",
                type: 'get',
                data: {title:$("#title").val(), classid:$("#classid").val()},
                dataType: "json",
                success:function(result){
                    excels = result.data;
                    table.exportFile('article-table', excels,'xls');
                }});
            return false;
      }
      else if (obj.event === 'collasped') {
        $('.user-left').toggleClass('user-collasped')
        $('.user-main').toggleClass('user-collasped')
        table.resize()
      }
    })

    form.on('submit(article-query)', function (data) {
      window.refresh(data.field)
      return false
    })

    form.on('switch(article-enable)', function (obj) {
      let status
      if (obj.elem.checked) {
        status = 1
      } else {
        status = 2
      }
      let loading = layer.load()
      $.ajax({
        url: '/admin/article/enable',
        data: JSON.stringify({ id: this.value, status:status}),
        dataType: 'json',
        contentType: 'application/json',
        type: 'put',
        success: function (result) {
          layer.close(loading)
          if (result.success) {
            popup.success(result.msg)
          } else {
            popup.failure(result.msg)
          }
        }
      })
    })

    window.add = function () {
      layer.open({
        type: 1,
        title: '新增',
        shade: 0.1,
        area: ['550px', '550px'],
        content: MODULE_PATH + 'add'
      })
    }

    window.edit = function (obj) {
      layer.open({
        type: 2,
        title: '修改文章',
        shade: 0.1,
        area: ['1350px', '800px'],
        content: MODULE_PATH + 'add/' + obj.data['articleId'],
        maxmin: true,
        offset: 't',
        scrollbar: false,
        anim:2,
      })
        console.log(obj.data)
    }
    window.remove = function (obj) {
      layer.confirm('确定要删除文章', { icon: 3, title: '提示' }, function (index) {
        layer.close(index)
        let loading = layer.load()
        $.ajax({
          url: MODULE_PATH + 'remove/' + obj.data['articleId'],
          dataType: 'json',
          type: 'delete',
          success: function (result) {
            layer.close(loading)
            if (result.success) {
              popup.success(result.msg, function () {
                obj.del()
              })
            } else {
              popup.failure(result.msg)
            }
          }
        })
      })
    }
    window.batchRemove = function (obj) {
      let data = table.checkStatus(obj.config.id).data
      if (data.length === 0) {
        layer.msg('未选中数据', {
          icon: 3,
          time: 1000
        })
        return false
      }
      var ids = []
      var hasCheck = table.checkStatus('article-table')
      var hasCheckData = hasCheck.data
         console.log(hasCheckData);
      if (hasCheckData.length > 0) {
        $.each(data, function (index, element) {
          ids.push(element.articleId)
        })
      }
      console.log(ids);
      layer.confirm('确定要删除选中文章', {
        icon: 3,
        title: '提示'
      }, function (index) {
        layer.close(index)
        let loading = layer.load()
        $.ajax({
          url: MODULE_PATH + 'batchRemove',
          data: { ids: ids },
          dataType: 'json',
          type: 'delete',
          success: function (result) {
            layer.close(loading)
            if (result.success) {
              popup.success(result.msg, function () {
                table.reload('article-table')
              })
            } else {
              popup.failure(result.msg)
            }
          }
        })
      })
    }
    window.refresh = function (param) {table.reload('article-table', { where: param })}
  })
</script>
</html>